package LUNCH;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

public class MainUI {
	public static Map<String, List<String[]>> map = new LinkedHashMap<String, List<String[]>>();
	private JFrame frame;
	private List<String> namelist = new ArrayList<String>();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainUI window = new MainUI();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainUI() {
		initialize();
	}

	public static String getCurrentTime() {
		SimpleDateFormat bartDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currentTime = bartDateFormat.format(date);
		return currentTime;
	}

	private Map<String, List<String[]>> getLunchInfo() {
		LunchInfoXml x = new LunchInfoXml("c:\\lunch.xml");
		Map<String, List<String[]>> map = null;
		try {
			map = x.readXML();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

	private void Add_To_Table(Map<String, List<String[]>> map,
			Vector tableContVect1) {
		Iterator<?> it1 = null;
		Map.Entry entry = null;
		it1 = map.entrySet().iterator();
		while (it1.hasNext()) {
			entry = (Map.Entry) it1.next();
			String name = (String) entry.getKey();
			namelist.add(name);
			List<String[]> list = (List<String[]>) entry.getValue();
			int len = list.size();
			for (int i = 0; i < len; i++) {
				String arr[] = list.get(i);
				tableContVect1.add(arr);
			}
		}
	}

	private CustJTable getTable() {
		Vector<?> tableContVect1 = new Vector<String[]>();
		Map<String, List<String[]>> map = getLunchInfo();
		Add_To_Table(map, tableContVect1);
		Vector<String> colNameVect1 = new Vector<String>();
		colNameVect1.add("姓名");
		colNameVect1.add("金额");
		colNameVect1.add("日期");
		colNameVect1.add("备注");
		CustJTable t = new CustJTable(tableContVect1, colNameVect1, 550, 350,
				new int[] { 136, 136, 136, 135 });
		JTextField editor = new JTextField();
		MyCellEditor cellEditor = new MyCellEditor(editor);
		cellEditor.setClickCountToStart(1);// 单击一次就可以进入编辑状态
		t.setRowHeight(40);
		t.getColumnModel().getColumn(0)
				.setCellEditor(new DefaultCellEditor(getNames()));
		t.getColumnModel().getColumn(1).setCellEditor(cellEditor);
		cellEditor.setTable(t);
		return t;
	}

	private JComboBox getNames() {
		String[] arr = namelist.toArray(new String[namelist.size()]);
		JComboBox comboBox = new JComboBox(arr);
		comboBox.setSize(130, 35);
		comboBox.setEditable(true);
		return comboBox;
	}

	private static boolean validate(String s, String regex) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(s);
		return m.matches();
	}

	public static void prt(Map<String, List<String[]>> map) {
		Iterator<?> it1 = null;
		Map.Entry entry = null;
		it1 = map.entrySet().iterator();
		while (it1.hasNext()) {
			entry = (Map.Entry) it1.next();
			System.out.println("姓名: " + entry.getKey());
			List<String[]> list = (List<String[]>) entry.getValue();
			int len = list.size();
			for (int i = 0; i < len; i++) {
				String arr[] = list.get(i);
				for (String value : arr) {
					System.out.println(value);
				}
				System.out
						.println("********************************************");
			}
		}
	}

	private Map<String, List<String[]>> getAllTableValue(CustJTable t) {
		//moneylist.clear();
		int rowCount = t.getRowCount();
		Map<String, List<String[]>> map = new LinkedHashMap<String, List<String[]>>();
		List<String[]> InfoList = null;
		for (int i = 0; i < rowCount; i++) {
			String name = "" + t.getValueAt(i, 0);
			if (name == null || name.length() == 0) {
				JOptionPane.showMessageDialog(null, "第" + (i + 1) + "行的姓名为空");
				return null;
			}
			String monery = "" + t.getValueAt(i, 1);
			String moneryreg = "\\d+(\\.\\d*)?";
			if (!validate(monery, moneryreg)) {
				JOptionPane.showMessageDialog(null, "第" + (i + 1) + "行第金额不是数字");
				return null;
			}
			if (monery == null || monery.length() == 0) {
				JOptionPane.showMessageDialog(null, "第" + (i + 1) + "行第金额为空");
				return null;
			}
			String date = "" + t.getValueAt(i, 2);
			String remark = "" + t.getValueAt(i, 3);
			String LunchInfo[] = new String[4];
			LunchInfo[0] = name;
			LunchInfo[1] = monery;
			LunchInfo[2] = date;
			LunchInfo[3] = remark;
			InfoList = map.get(name);
			if (InfoList != null) {
				InfoList.add(LunchInfo);
			} else {
				InfoList = new ArrayList<String[]>();
				InfoList.add(LunchInfo);
				map.put(name, InfoList);
			}
		}
		// prt(map);
		return map;
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		final CustJTable t = getTable();
		frame = new JFrame();
		frame.setBounds(100, 100, 585, 445);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = frame.getSize();
		if (frameSize.height > screenSize.height)
			frameSize.height = screenSize.height;
		if (frameSize.width > screenSize.width)
			frameSize.width = screenSize.width;
		frame.setLocation((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.height) / 2);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		JScrollPane scrollPane = new JScrollPane(t);
		scrollPane.setBounds(10, 10, 555, 334);
		frame.getContentPane().add(scrollPane);

		JButton btnNewButton = new JButton("添加");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Vector vec = new Vector<String>();
				Object l1[] = { "威威", "", getCurrentTime(), "" };
				vec.add(l1);
				t.getModel().addRows(vec);
				Rectangle rect = t.getCellRect(t.getRowCount(), 0, true);
				t.scrollRectToVisible(rect);// 跳到最后一行
			}
		});
		btnNewButton.setBounds(10, 354, 123, 43);
		frame.getContentPane().add(btnNewButton);

		JButton button = new JButton("删除");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int[] selectRow = t.getSelectedRows();
				for (int i : selectRow) {
					System.out.println("选中行" + i);
				}
				t.getModel().removeRows(selectRow);
			}
		});
		button.setBounds(153, 354, 123, 43);
		frame.getContentPane().add(button);

		JButton button_1 = new JButton("保存");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				List<String[]> savelList = null;
				Map<String, List<String[]>> map = getAllTableValue(t);
				new CreateXML(map);
			}
		});
		button_1.setBounds(298, 354, 123, 43);
		frame.getContentPane().add(button_1);

		JButton button_2 = new JButton("合计");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				List<String[]> totalList = null;
				Map<String, List<String[]>> total = new LinkedHashMap<String, List<String[]>>();
				getAllTableValue(t);// TODO
				t.getModel().removeAllRows();
			}
		});
		button_2.setBounds(442, 354, 123, 43);
		frame.getContentPane().add(button_2);
	}

	class MyCellEditor extends DefaultCellEditor {
		CustJTable table;

		public CustJTable getTable() {
			return table;
		}

		public void setTable(CustJTable table) {
			this.table = table;
		}

		public MyCellEditor(final JTextField textField) {
			super(textField);
			textField.addKeyListener(new KeyListener() {
				public void keyTyped(KeyEvent e) {

				}

				public void keyPressed(KeyEvent e) {

				}

				public void keyReleased(KeyEvent e) {
					int row = getTable().getSelectedRow();
					int column = getTable().getSelectedColumn();
					getTable().setValueAt(textField.getText(), row, column);
					getTable().repaint();
				}
			});
		}
	}
}
